<template>
  <el-container>
    <el-header :height="headerHeight">
      <el-form label-width="120px" label-position="left" style="margin-top:10px">
        <el-form-item label="用户名称：">
          <el-input v-model="userName" clearable style="width:400px" @keyup.enter.native="handelKeyDown"
            @clear="handleQuery" />
        </el-form-item>
        <el-form-item label="角色名称：">
          <el-select v-model="userRole" placeholder="请选择" style="width:400px" clearable filterable @change="handleQuery">
            <el-option v-for="item in userRoles" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="userStatus" @change="handelStatusChange">
            <el-radio-button label="全部" />
            <el-radio-button label="启用" />
            <el-radio-button label="禁用" />
          </el-radio-group>
        </el-form-item>
        <el-button v-if="btnAip.add.buttonCaption" type="primary" @click="OnBtnAdd">{{ btnAip.add.buttonCaption }}
        </el-button>
        <el-button v-if="btnAip.query.buttonCaption" type="primary" @click="handleQuery">
          {{ btnAip.query.buttonCaption }}</el-button>
      </el-form>
    </el-header>
    <el-main :height="mainHeight">
      <el-table :data="tableData" border fit empty-text="没有查询到数据" highlight-current-row :height="mainHeight"
        @sort-change="handelSortChange">
        <el-table-column type="index" label="序号" />
        <el-table-column v-if="false" prop="id" label="id" />
        <el-table-column prop="userName" label="用户名称" sortable />
        <el-table-column prop="loginName" label="登录账号" />
        <el-table-column prop="loginPwd" label="登录密码">
          <template>******</template>
        </el-table-column>
        <el-table-column v-if="false" prop="roleId" label="角色ID" />
        <el-table-column prop="tel" label="手机账号" />
        <el-table-column prop="tRolesRoleName" label="角色名称" />
        <el-table-column prop="deptName" label="部门名称" />
        <el-table-column prop="status" label="启用状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == true" type="success">启用</el-tag>
            <el-tag v-if="scope.row.status == false" type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isAuditer" label="是否审核员">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isAuditer == true" type="success">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column v-if="false" prop="createId" label="创建人ID" />
        <el-table-column label="操作" fixed="right" width="100px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light"  content="编辑数据" placement="top">
              <el-button v-if="btnAip.edit.buttonCaption" icon="el-icon-edit" circle
              @click="handleEdit(scope.$index, scope.row)" />
              </el-tooltip>
              <el-tooltip class="item" effect="light"  content="删除数据" placement="top">
            <el-button v-if="btnAip.delete.buttonCaption" type="danger" icon="el-icon-delete" circle
              @click="handleDelete(scope.$index, scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer :height="footerHeight">
      <el-pagination background layout="prev, pager, next" :page-size="pageSize" :total="totalCount"
        :current-page="pageIndex" @current-change="handlePaging" />
    </el-footer>
    <el-dialog title="编辑用户信息" :visible.sync="dialogVisible" width="45%">
      <el-form ref="formData" :model="formData" label-width="100px" :rules="formRules">
        <el-form-item label="系统编号：" prop="id">
          <el-input v-model="formData.id" placeholder="系统生成" readonly />
        </el-form-item>
        <el-form-item label="用户名称：" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="登录账号：" prop="loginName">
          <el-input v-model="formData.loginName" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="登录密码：" prop="loginPwd">
          <el-input v-model="formData.loginPwd" placeholder="请输入登录密码" show-password />
        </el-form-item>
        <el-form-item label="手机号码" >
          <el-input v-model="formData.tel" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="角色名称：">
          <el-select v-model="formData.roleId" filterable placeholder="请选择" clearable>
            <el-option v-for="item in userRoles" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称：">
          <el-select v-model="formData.deptId" filterable placeholder="请选择" clearable>
            <el-option v-for="item in deptNames" :key="item.id" :label="item.deptName" :value="item.id" />
          </el-select>
        </el-form-item>   
        <el-form-item label="启用状态：">
          <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="是否审核员：">
          <el-switch v-model="formData.isAuditer" active-text="是" inactive-text="否" />
        </el-form-item>           
        <el-form-item v-if="supplierSelectVisiable" label="供应商名称:">
          <el-select v-model="formData.supplierId" placeholder="请选择供应商">
            <el-option v-for="item in supplierOptions" :key="item.id" :value="item.id" :label="item.gysqc">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="OnBtnClose">关闭</el-button>
        <el-button type="primary" @click="OnBtnSaveSubmit">保存</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import RequestObject from '@/utils/requestObject'
import request from '@/utils/request'
import { MessageBox } from 'element-ui'
import DateUtil from '@/utils/dateUtil'
import height from '@/utils/height'
import { getBtnCtr } from '@/utils/BtnControl'

export default {
  name: "PlatformUser",
  data() {
    var checkName = (rule, value, callback) => {
      const phoneReg = /^1[3|5|6|7|8|9][0-9]{9}$/;
      if (!value) {
        return callback(new Error("请输入手机号码"));
      }
      if (phoneReg.test(value)) {
        callback();
      } else {
        callback(new Error("手机号码格式不正确"));
      }
    };
    return {
      btnAip: '',
      headerHeight: '180px',
      mainHeight: '',
      footerHeight: '50px',
      tableData: null, // table数据模型
      dialogVisible: false, // 编辑窗口是否显示
      userRoles: null, // 角色数据
      formData: {
        id: 0,
        userName: '',
        loginName: '',
        loginPwd: '',
        roleId: null,
        deptId: null,
        deptName: '',
        status: true,
        createTime: new Date(),
        createId: 0,
        isSupplier: '否',
        supplierId: undefined,
        tel: '',
        xxid: [],
        bzid:[],
        isAuditer: false,
      },
      formRules: {
        userName: [{
          required: true,
          message: '请输入用户姓名',
          trigger: 'blur'
        }, {
          min: 1,
          max: 12,
          message: '用户姓名须在1到12个字符之间',
          trigger: 'blur'
        }],
        loginName: [{
          required: true,
          message: '请输入登录账号',
          trigger: 'blur'
        }, {
          min: 3,
          max: 12,
          message: '登录账户须在3到12个字符之间',
          trigger: 'blur'
        }],
        loginPwd: [{
          required: true,
          message: '请输入登录密码',
          trigger: 'blur'
        }, {
          min: 8,
          max: 16,
          message: '登录密码须在8到16个字符之间',
          trigger: 'blur'
        }]
      },
      pageSize: 25, // 分页显示记录条数
      totalCount: 0, // 总记录数
      pageIndex: 1, // 页码
      sortColumn: '', // 排序字段
      sortOrder: '', // 排序规则
      userRole: null, // 角色
      userName: '', // 菜单名称查询条件
      userStatus: '全部', // 菜单状态
      deptNames: [],
      supplierSelectVisiable: false,
      supplierOptions: [],
      XxList: []
    }
  },
  created() {
    this.mainHeight =
      (height -
        116 -
        parseInt(this.headerHeight) -
        parseInt(this.footerHeight)).toString() +
      'px'

    // 初始化角色数据
    this.GetRoles();

    // 初始化部门数据
    this.GetDepts();

    // 初始化表格数据
    this.handleQuery()    

    // 动态头部按钮
    this.btnAip = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )

  },
  methods: {
    GetRoles() {
      var reqObject = RequestObject.CreateGetObject()
      request({
        url: '/api/troles',
        method: 'get',
        params: {
          requestObject: reqObject
        }
      }).then(res => {
        if (res.code == -1) {
          this.$confirm(res.info, '错误信息', {
            confirmButtonText: '确定',
            type: 'error',
            showCancelButton: false
          })
        } else {
          this.userRoles = res.data
        }
      })
    },
    GetDepts() {
      var reqObject = RequestObject.CreateGetObject()
      request({
        url: '/api/tpmdept',
        method: 'get',
        params: {
          requestObject: reqObject
        }
      }).then(res => {
        if (res.code == -1) {
          this.$confirm(res.info, '错误信息', {
            confirmButtonText: '确定',
            type: 'error',
            showCancelButton: false
          })
        } else {
          this.deptNames = res.data
        }
      })
    },
    handleIsSupplierChange(value) {
      if (value === '是') {
        this.supplierSelectVisiable = true;
      } else {
        this.supplierSelectVisiable = false;
      }
    },
    handleQuery() {
      var queryConditions = []
      var orderConditions = []
      if (this.userRole && this.userRole !== '' && this.userRole !== null) {
        queryConditions.push({
          column: 'roleId',
          content: this.userRole,
          condition: 0
        })
      }
      if (this.userName && this.userName.length > 0) {
        queryConditions.push({
          column: 'userName',
          content: this.userName,
          condition: 6
        })
      }
      if (this.userStatus != '全部') {
        queryConditions.push({
          column: 'Status',
          content: this.userStatus == '启用' ? '1' : '0',
          condition: 0
        })
      }
      if (this.sortColumn && this.sortColumn.length > 0) {
        orderConditions.push({
          column: this.sortColumn,
          condition: this.sortOrder
        })
      }
      var queryRequest = RequestObject.CreateGetObject(
        true,
        this.pageSize,
        this.pageIndex,
        queryConditions,
        orderConditions
      )
      request({
        url: '/api/tusers',
        method: 'get',
        params: {
          requestObject: JSON.stringify(queryRequest)
        }
      })
        .then(res => {
          this.tableData = res.data
          this.totalCount = res.totalNumber
        })
        .catch(() => {
          this.$message('error')
        })
    },
    OnBtnAdd() {
      this.formData.id = 0
      this.formData.userName = ''
      this.formData.loginName = ''
      this.formData.loginPwd = ''
      this.formData.roleId = -1
      this.formData.deptId = -1;
      this.formData.status = true
      this.formData.createTime = new Date()
      this.formData.createId = 0
      this.formData.tel = undefined
      this.formData.isAuditer = false
      this.dialogVisible = true
    },
    handleEdit(index, selectedRow) {
      this.formData.id = selectedRow.id
      this.formData.userName = selectedRow.userName
      this.formData.loginName = selectedRow.loginName
      this.formData.loginPwd = selectedRow.loginPwd
      this.formData.roleId = selectedRow.roleId
      this.formData.deptId = selectedRow.deptId
      this.formData.deptIds = selectedRow.deptIds;
      this.formData.status = selectedRow.status
      this.formData.createId = selectedRow.createId
      this.formData.tel = selectedRow.tel;
      this.formData.isAuditer = selectedRow.isAuditer;
      this.dialogVisible = true
    },
    handleDelete(index, selectedRow) {
      this.$confirm('是否确定并删除该按钮信息?', '确认对话框', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showConfirmButton: true
      }).then(() => {
        var deleteData = RequestObject.CreatePostObject(selectedRow.id)
        request({
          url: '/api/tusers/byid',
          method: 'delete',
          data: deleteData
        }).then(res => {
          if (res.code == -1) {
            this.$confirm(res.info, '错误信息', {
              confirmButtonText: '确定',
              type: 'error',
              showCancelButton: false
            })
          } else {
            this.$message({
              message: '删除数据成功',
              type: 'success'
            })
            this.handleQuery() // 查询数据
          }
        })
      })
    },
    OnBtnSaveSubmit() {
      this.$refs.formData.validate(valid => {
        if (!valid) {
          this.$message({
            message: '数据不合法，无法保存',
            type: 'error'
          })
        } else {

          if (this.formData.isSupplier === '是' && this.formData.supplierId < 1) {
            this.$message({
              type: "error",
              message: "请选择供应商名称"
            });
            return;
          }
          var currData = this.GetPostData()
          var currMethod = 'post'
          if (currData.id !== 0) {
            // 修改
            currMethod = 'put'
          }
          var data = RequestObject.CreatePostObject(currData)
          request({
            url: '/api/tusers',
            method: currMethod,
            data: data
          }).then(res => {
            if (res.code == -1) {
              this.$confirm(res.info, '错误信息', {
                confirmButtonText: '确定',
                type: 'error',
                showCancelButton: false
              })
            } else {
              this.$message({
                message: '保存数据成功',
                type: 'success'
              })
              this.$refs.formData.resetFields()
              this.dialogVisible = false
              this.handleQuery() // 查询数据
            }
          })
        }
      })
    },
    OnBtnClose() {
      this.dialogVisible = false
      this.$refs.formData.resetFields()
    },
    GetPostData() {
      var result = {
        id: this.formData.id,
        deptId: this.formData.deptId,
        userName: this.formData.userName,
        loginName: this.formData.loginName,
        loginPwd: this.formData.loginPwd,
        roleId: this.formData.roleId,
        status: this.formData.status,
        createId: 0,
        tel: this.formData.tel,
        isAuditer: this.formData.isAuditer
      }
      return result
    },
    handlePaging(index) {
      this.pageIndex = index
      this.handleQuery()
    },
    handelStatusChange() {
      this.handleQuery()
    },
    handelSortChange(currSort) {
      this.sortColumn = currSort.prop
      this.sortOrder = currSort.order == 'ascending' ? 'asc' : 'desc'
      this.handleQuery()
    },
    handelDatePicker() {
      this.handleQuery()
    },
    handelKeyDown() {
      this.handleQuery()
    },
    handleAppChange(value) {
      this.handleQuery()
    }
  }
}
</script>
